import Vue from 'vue'
import Vuex from 'vuex'
import { getMenuList } from '../api/index'
import recursionRoutes from '@/utils/recursionRoutes'
import allRoutes from '@/router/allRoutes'
import dynamicRoutes from '../router/dynamicRoutes'
import router from '../router/index'
Vue.use(Vuex)

//侧边菜单栏思路
//发送请求，获取菜单名
//通过递归函数计算路由配置
//将计算好的路由配置，添加到home路由的children中

export default new Vuex.Store({
  state: {
    sideMenu: []
  },
  mutations: {
    SET_SIDEMENU (state, payload) {
      state.sideMenu = payload
      //在dynamicRoutes中查找，并返回值
      console.log(state.sideMenu);
      let target = dynamicRoutes.find(item => {
        return item.path === "/"
      })
      //给target添加children 路由
      target.children = state.sideMenu
      // 将dynamicRoutes添加到项目中
      router.addRoutes(dynamicRoutes);
    }
  },
  actions: {
    async FETCH_MENULIST ({ commit }) {
      //发送请求，拿到用户菜单名称
      let res = await getMenuList()
      // console.log(res);
      if (res.data.state && res.data.menuList.length > 0) {
        //调用recursionRoutes 计算用户路由配置
        let Menu = recursionRoutes(res.data.menuList, allRoutes)
        commit("SET_SIDEMENU", Menu)  //通过commit 将用户路由配置传给payload
      } else {
        console.log("获取用户路由失败!");
        router.push('/login')
      }
    }
  },
  modules: {
  }
})
